package com.jianzhile.jobs.utils;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.widget.EditText;

import com.android.volley.NoConnectionError;
import com.android.volley.ServerError;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.jianzhile.jobs.R;
import com.jianzhile.jobs.bean.EncryptBean;
import com.jianzhile.jobs.encrypt.AES;
import com.jianzhile.jobs.encrypt.ConvertUtils;
import com.jianzhile.jobs.encrypt.Digest;
import com.jianzhile.jobs.encrypt.KEY;
import com.jianzhile.jobs.encrypt.RSA;
import com.jianzhile.jobs.encrypt.RandomUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;

@SuppressLint("SimpleDateFormat")
public class CommonUtil {
    private Context mContext;
    public String imei;

    public void init(Context context) {
        mContext = context;
        imei = Digest.signMD5(GetMachineInfo.getAndroidId(mContext), "UTF-8")
                .toLowerCase();
    }

    private static CommonUtil instance;

    public static CommonUtil getInstance() {
        if (instance == null) {
            instance = new CommonUtil();
        }
        return instance;
    }

    /**
     * Returns specified application cache directory. Cache directory will be
     * created on SD card by defined path if card is mounted. Else - Android
     * defines cache directory on device's file system.
     *
     * @param context Application context
     * @return Cache {@link File directory}
     */
    public static File getImgCacheDirectory(Context context) {
        return getOwnCacheDirectory(context, "/banana/imgs");
    }

    public static File getOwnCacheDirectory(Context context, String cacheDir) {
        File appCacheDir = null;
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            appCacheDir = new File(Environment.getExternalStorageDirectory(),
                    cacheDir);
        }
        if (appCacheDir == null
                || (!appCacheDir.exists() && !appCacheDir.mkdirs())) {
            appCacheDir = context.getCacheDir();
        }
        return appCacheDir;
    }


    public static void showInfoDialog(Context context, String message) {
        showInfoDialog(context, message, "提示", "确定", null);
    }

    public static void showInfoDialog(Context context, String message,
                                      String titleStr, String positiveStr,
                                      DialogInterface.OnClickListener onClickListener) {
        AlertDialog.Builder localBuilder = new AlertDialog.Builder(context);
        localBuilder.setTitle(titleStr);
        localBuilder.setMessage(message);
        if (onClickListener == null)
            onClickListener = new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {

                }
            };
        localBuilder.setPositiveButton(positiveStr, onClickListener);
        localBuilder.show();
    }

    private static SimpleDateFormat sdf = new SimpleDateFormat("MM/dd");
    private static SimpleDateFormat ms = new SimpleDateFormat("mm:ss");

    public static String timeStampToString(long mill) {
        Date date = new Date(mill);
        String strs = "";
        try {
            strs = sdf.format(date);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return strs;
    }

    public static String MillisToString(long mill) {
        Date date = new Date(mill);
        String strs = "";
        try {
            strs = ms.format(date);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return strs;
    }

    private static SimpleDateFormat dateFormat = new SimpleDateFormat(
            "MM/dd HH:mm");
    private static SimpleDateFormat dateFormatFull = new SimpleDateFormat(
            "yyyy年MM月dd日 HH:mm");

    public static String formatDate(String timestamp) {
        if (TextUtils.isEmpty(timestamp)) {
            return "";
        }
        BigDecimal decimal = new BigDecimal(timestamp).multiply(new BigDecimal(
                1000));
        long temp = decimal.longValue();
        String state_time = dateFormat.format(temp);
        return state_time;
    }

    public static String formatDateFull(long timestamp) {
        return dateFormatFull.format(timestamp);
    }

    public static String countDownTimer(long time) {
        if (time <= 0) {
            return "";// 支付超时
        }
        long minute = time / (1 * 60) % 60;
        long second = time / (1) % 60;
        String minStr, secondStr;
        minStr = minute < 10 ? "0" + minute : "" + minute;
        secondStr = second < 10 ? "0" + second : "" + second;

        return minStr + ":" + secondStr;
    }

    public static String encry(String content) throws Exception {
        String aesKey = RandomUtil.getRandom(16);
        String data = AES.encryptToBase64(content, aesKey);
        String encryptKey = RSA.encrypt(aesKey, KEY.publicKey);
        EncryptBean bean = new EncryptBean();
        bean.data = data;
        bean.encryptKey = encryptKey;
        Gson gson = new Gson();
        return gson.toJson(bean);
    }

    public static String deEncry(String object) {
        try {
            Gson gson = new Gson();
            EncryptBean bean = gson.fromJson(object, EncryptBean.class);
            // 获取aesKEY
            String enkey = RSA.decrypt(bean.encryptKey, KEY.privateKey);
            return AES.decryptFromBase64(bean.data, enkey);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String deEncry(JSONObject object) {
        try {
            // 获取aesKEY
            String enkey = RSA.decrypt(object.optString("encryptKey"),
                    KEY.privateKey);
            return AES.decryptFromBase64(object.optString("data"), enkey);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public HashMap<String, String> getParams(HashMap<String, String> params
    ) {
        Gson gosn = new Gson();
        HashMap<String, String> param = new HashMap<String, String>();
        // params.put("m", action);
        // int userId = SharePreUtil.getInstance().getInt(Const.KEY_USER_ID);
        // if (userId != -1) {
        // params.put("userid", String.valueOf(userId));
        // }
        try {
            param.put("c", CommonUtil.encry(gosn.toJson(params)));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return param;
    }

    /**
     * 获取以对像为主的参数
     *
     * @param content
     * @param action
     * @return
     */
    /*
     * public HashMap<String, String> getParams(Object content, String action) {
	 * Gson gosn = new Gson(); HashMap<String, String> params = new
	 * HashMap<String, String>(); try { JSONObject json = new
	 * JSONObject(gosn.toJson(content)); json.put("m", action); int userId =
	 * SharePreUtil.getInstance().getInt(Const.KEY_USER_ID); if (userId != -1) {
	 * json.put("userid", String.valueOf(userId)); } params.put("c",
	 * CommonUtil.encry(json.toString()));
	 * 
	 * } catch (JSONException e) { e.printStackTrace(); } catch (Exception e) {
	 * e.printStackTrace(); } return params; }
	 */

    /**
     * 获取以对像为主的参数
     *
     * @param content
     * @param action
     * @return
     */
    // public HashMap<String, String> getParams(Object content) {
    // Gson gosn = new Gson();
    // HashMap<String, String> params = new HashMap<String, String>();
    // try {
    // JSONObject json = new JSONObject(gosn.toJson(content));
    // json.put("t", 20);
    // json.put("e", android.os.Build.MODEL);
    // json.put("b", imei);
    // json.put("p", SharePreUtil.getInstance().getString("user_phone"));
    //
    // params.put("c", CommonUtil.encry(json.toString()));
    //
    // } catch (JSONException e) {
    // e.printStackTrace();
    // } catch (Exception e) {
    // e.printStackTrace();
    // }
    // return params;
    // }
    public HashMap<String, String> getParams(Object content) {
        Gson gosn = new Gson();
        HashMap<String, String> params = new HashMap<String, String>();
        try {
            JSONObject json = new JSONObject(gosn.toJson(content));
            json.put("e", android.os.Build.MODEL);
            json.put("b", imei);
            json.put("p", SharePreUtil.getInstance().getString("user_phone"));
            params.put("c", CommonUtil.encry(json.toString()));

        } catch (JSONException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        Log.i("CommonUtil", params.toString());
        return params;
    }

    /**
     * 判断当前是否有可用的网络以及网络类型 0：无网络 1：WIFI 2：CMWAP 3：CMNET
     *
     * @param context
     * @return
     */
    public static int isNetworkAvailable(Context context) {
        ConnectivityManager connectivity = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity == null) {
            return 0;
        } else {
            NetworkInfo[] info = connectivity.getAllNetworkInfo();
            if (info != null) {
                for (int i = 0; i < info.length; i++) {
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                        NetworkInfo netWorkInfo = info[i];
                        if (netWorkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                            return 1;
                        } else if (netWorkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
                            String extraInfo = netWorkInfo.getExtraInfo();
                            if ("cmwap".equalsIgnoreCase(extraInfo)
                                    || "cmwap:gsm".equalsIgnoreCase(extraInfo)) {
                                return 2;
                            }
                            return 3;
                        }
                    }
                }
            }
        }
        return 0;
    }

    public void handleError(Context context, VolleyError error) {
        if (error instanceof TimeoutError) {
            ToastUtils.showBottomToast(context, R.string.time_out);
        } else if (error instanceof NoConnectionError) {
            ToastUtils.showBottomToast(context, R.string.net_eror);
        } else if (error instanceof ServerError) {
            ToastUtils.showBottomToast(context, R.string.server_error);
        }

    }

    /**
     * 判断edittext是否null
     */
    public static String checkEditText(EditText editText) {
        if (editText != null && editText.getText() != null
                && !(editText.getText().toString().trim().equals(""))) {
            return editText.getText().toString().trim();
        } else {
            return "";
        }
    }


    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    public static boolean hasSdcard() {
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            String saveDir = Const.TAKE_PICTURE_PATH;
            File dir = new File(saveDir);
            if (!dir.exists()) {
                dir.mkdir();
            }
            return true;
        } else {
            return false;
        }
    }

    public static Bitmap getUriBitmap(Context context, Uri uri, int reqWidth,
                                      int reqHeight) {
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        newOpts.inJustDecodeBounds = true;
        Bitmap bitmap = decodeUriAsBitmap(context, uri, newOpts);
        newOpts.inJustDecodeBounds = false;
        newOpts.inSampleSize = calculateInSampleSize(newOpts, reqWidth,
                reqHeight);
        bitmap = decodeUriAsBitmap(context, uri, newOpts);
        return bitmap;
    }

    public static Bitmap decodeUriAsBitmap(Context context, Uri uri,
                                           BitmapFactory.Options options) {

        Bitmap result = null;

        if (uri != null) {
            ContentResolver cr = context.getContentResolver();
            InputStream inputStream = null;
            try {
                inputStream = cr.openInputStream(uri);
                result = BitmapFactory.decodeStream(inputStream, null, options);
                inputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return result;
    }

    public static int calculateInSampleSize(BitmapFactory.Options options,
                                            int reqWidth, int reqHeight) {
        // Raw height and width of image
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {
            if (width > height) {
                inSampleSize = Math.round((float) height / (float) reqHeight);
            } else {
                inSampleSize = Math.round((float) width / (float) reqWidth);
            }
        }
        return inSampleSize;
    }

    /**
     * 读取图片属性：旋转的角度
     *
     * @param path 图片绝对路径
     * @return degree旋转的角度
     */
    public static int readPictureDegree(String path) {
        int degree = 0;
        try {
            ExifInterface exifInterface = new ExifInterface(path);
            int orientation = exifInterface.getAttributeInt(
                    ExifInterface.TAG_ORIENTATION,
                    ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return degree;
    }

    /*
     * 旋转图片
     *
     * @param angle
     *
     * @param bitmap
     *
     * @return Bitmap
     */
    public static Bitmap rotateBitmap(int degree, Bitmap bm) {
        if (degree == 0) {
            return bm;
        }
        Bitmap returnBm = null;

        // 根据旋转角度，生成旋转矩阵
        Matrix matrix = new Matrix();
        matrix.postRotate(degree);
        try {
            Log.i("jacky", "rotate: " + degree);
            // 将原始图片按照旋转矩阵进行旋转，并得到新的图片
            returnBm = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(),
                    bm.getHeight(), matrix, true);
        } catch (OutOfMemoryError e) {
        }
        if (returnBm == null) {
            returnBm = bm;
        }
        if (bm != returnBm) {
            bm.recycle();
        }
        return returnBm;
    }

    /**
     * 图片保存到SD卡
     *
     * @param bitmap
     * @param fileName
     * @return
     */
    public static String saveBitToSD(Bitmap bitmap, String fileName) {
        if (bitmap == null || bitmap.isRecycled()) {
            return "";
        }

        File file = new File(Const.TAKE_PICTURE_PATH);
        File dirFile = new File(file.getAbsolutePath());
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
        File pathFile = new File(dirFile, fileName);
        bitmap2File(bitmap, pathFile.getAbsolutePath());
        return pathFile.getAbsolutePath();
    }

    /**
     * 图片保存到文件
     *
     * @param bitmap
     * @param fileName
     */
    public static void bitmap2File(Bitmap bitmap, String fileName) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(fileName);
            fos.write(baos.toByteArray());
            fos.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (fos != null)
                    fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 获取屏幕宽度
     *
     * @param context
     * @return
     */
    public static int getDisplayWidth(Context context) {
        return context.getResources().getDisplayMetrics().widthPixels;
    }

    /**
     * 获取屏幕高度
     *
     * @param context
     * @return
     */
    public static int getDisplayHight(Context context) {
        return context.getResources().getDisplayMetrics().heightPixels;
    }

    public static String md5(InputStream fis) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            // 100KB each time
            byte[] buffer = new byte[102400];
            int length;
            while ((length = fis.read(buffer)) != -1) {
                md.update(buffer, 0, length);
            }
            return ConvertUtils.asHex(md.digest());
        } catch (Exception e) {
            return null;
        } finally {
            try {
                if (fis != null)
                    fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static String md5(File file) {
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream(file);
            String md5 = md5(inputStream);
            return md5;
        } catch (Exception e) {
            return null;
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }


    /**
     * 将长时间格式字符串转换为时间 yyyy-MM-dd HH:mm:ss
     */
    public static String getStringDate(Long date) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = formatter.format(date);
        return dateString;
    }

    /**
     * 获取当前日期
     *
     * @return
     */
    public static String getCurrentDateString() {
        String result = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",
                Locale.getDefault());
        Date nowDate = new Date();
        result = sdf.format(nowDate);
        return result;
    }


    public static String getAge(Date birth) {

        Date date = new Date();
        long day = (date.getTime() - birth.getTime()) / (24 * 60 * 60 * 1000) + 1;
        String year = new java.text.DecimalFormat("#").format(day / 365f);
        return year;
    }
}
